package com.yuhong.reggie.controller;

import com.yuhong.reggie.common.R;
import com.yuhong.reggie.entity.ShoppingCart;
import com.yuhong.reggie.service.ShoppingCartSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired(required = false)
    private ShoppingCartSerivce shoppingCartSerivce;

    @RequestMapping("/sub")
    public R<ShoppingCart> subCart(@RequestBody ShoppingCart shoppingCart,HttpSession session){
        Long userId = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userId);

        ShoppingCart subCart = shoppingCartSerivce.subCart(shoppingCart);
        return R.success(subCart);
    }

    @DeleteMapping("/clean")
    public R<String> delete(Long id){
        Integer delete = shoppingCartSerivce.delete(id);

        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> findShopping(HttpSession session){
        Long loginId = (Long) session.getAttribute("user");

        List<ShoppingCart> shopping = shoppingCartSerivce.findShopping(loginId);

        if (shopping.size()>0) {
            for (int i = shopping.size() - 1; i >= 0; i--) {
                ShoppingCart shoppingCart = shopping.get(i);
                if (shoppingCart.getNumber() == 0) {
                    shopping.remove(shoppingCart);
                }
            }
        }
            return R.success(shopping);


    }

    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //封装数据到ShoppingCart中去
        //获取登录id封装到shopping对象中
        Long userID = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userID);
        //调用业务添加购物车
        ShoppingCart shoppingCartNew = shoppingCartSerivce.addCart(shoppingCart);
        //返回
        return R.success(shoppingCartNew);
    }
}
